package com.ferry.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Created by daiyong
 */
public class SystemPropertyUtil {

	private static final Logger logger = LoggerFactory.getLogger(SystemPropertyUtil.class);

	//私有构造函数
	private SystemPropertyUtil(){}

	public static String get(String key) {
		return get(key, null);
	}

	public static String get(String key, String defultValue) {
		if (key == null) {
			throw new NullPointerException("key不能为null.");
		}
		if (key.isEmpty()) {
			throw new IllegalArgumentException("key不能为空.");
		}

		String value = null;
		try {
			if (System.getSecurityManager() == null) {
				value = System.getProperty(key);
			} else {
				value = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key));
			}
		} catch (Exception e) {
			logger.warn("从系统中获取不到值，使用默认值.",
						key, StackTraceUtil.stackTrace(e));
		}

		if (value == null) {
			return defultValue;
		}

		return value;
	}

	/**
	 * 设置参数
	 * @param key
	 * @param value
	 * @return
	 */
	public static Object setPropertity(String key, String value) {
		return System.getProperties().setProperty(key, value);
	}
}
